import { ref } from 'vue'
import { defineStore } from 'pinia'
import { computedAsync } from '@vueuse/core'
import api from '@/api/student'
import lessonApi from '@/api/lesson'
import type { PageConfig, StudentStudyListItem, StudentItem, LessonItem } from '@/config/types'
import type { LessonStudyParam } from '@/config/forms'
import cfg from '@/config/config'
import { useStudentStudyStore } from './studentStudy'



export const useStudentLessonStudyStore = defineStore('studentLessonStudy', () => {
    const loading = ref<boolean>(false)
    const search = ref<LessonStudyParam>({
        accountId: 0,
        lessonId: 0,
        page: 1,
        limit: cfg.pageLimit
    })
    const pager = ref<PageConfig>({
        page: 1,
        pageSize: cfg.pageLimit,
        total: 0
    })
    const student = computedAsync<StudentItem | null>(async() => {
        if (search.value.accountId === 0) {
            return null
        }
        const store = useStudentStudyStore()
        await store.loadStudent(search.value.accountId)
        return store.student
    }, null)
    const lesson = ref<LessonItem | null>(null)
    const items = ref<StudentStudyListItem[]>([])

    async function loadItems(accountId: number, lessonId: number) {
        if (search.value.accountId === accountId &&
            search.value.lessonId === lessonId &&
            search.value.page === pager.value.page &&
            search.value.limit === pager.value.pageSize
        ) {
            return
        }
        await loadLesson(lessonId)
        search.value.accountId = accountId
        search.value.lessonId = lessonId
        loading.value = true
        try {
            const res = await api.getLessonStudyLog(search.value)
            items.value = res.data
            pager.value = {
                page: res.page,
                pageSize: res.size,
                total: res.total
            }
            loading.value = false
        } catch(e) {
            loading.value = false
        }
    }

    async function changePage(page: number, size: number) {
        search.value.page = page
        search.value.limit = size
        loadItems(search.value.accountId, search.value.lessonId)
    }

    async function loadLesson(lessonId : number) {
        if (lesson.value && lesson.value.id === lessonId) {
            return
        }
        loading.value = true
        try {
            const res = await lessonApi.getItem(lessonId)
            lesson.value = res.data
            loading.value = false
        } catch(e) {
            loading.value = false
        }
    }

    return {
        loading,
        search,
        pager,
        student,
        lesson,
        items,

        loadItems,
        changePage
    }
})